﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using TSV.Models;
using TSV.Areas.Administration.Models;
using TSV.Library.Common;
using TSV.Library.Attributes;

namespace TSV.Areas.Administration.Controllers
{
    public class UserAdminController : BaseController
    {
        private UserAdminDao accDao = new UserAdminDao();
        private GroupDao groupDao = new GroupDao();
        // GET: /UserAdmin/

        [CrmAuthorizeAttribute(Module = Modules.QL_Nguoi_Dung, Rights = Permissions.Doc)]
        public ActionResult Index()
        {
            ViewData["GroupName"] = new SelectList(groupDao.GetList(), "GroupId", "Groupname", "");
            return View();
        }

        [CrmAuthorizeAttribute(Module = Modules.QL_Nguoi_Dung, Rights = Permissions.Doc)]
        public ActionResult GetListJQGrid(string name, string groupName)
        {

            #region JQGrid Params
            string sortColumn = (Request.Params[GridConstants.SORT_COLUMN]).ToString();
            string sortOrder = (Request.Params[GridConstants.SORT_ORDER]).ToString();
            int pageIndex = Convert.ToInt32(Request.Params[GridConstants.PAGE_INDEX]);
            int rowCount = Convert.ToInt32(Request.Params[GridConstants.ROW_COUNT]);
            #endregion


            List<User_Group> accList = accDao.GetListUser_Group();
            if ((!string.IsNullOrEmpty(name) && name != Constants.USERNAME))
            {

                accList = accList.Where(p => p.UserAdmin.UserName.ToLower().Contains(name.ToLower())).ToList<User_Group>();                
            }

            if(!string.IsNullOrEmpty(groupName))
            {
                accList = accList.Where(p => p.GroupId == int.Parse(groupName)).ToList<User_Group>();
            }

            int totalRecords = accList.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)rowCount);
            int currentPage = CommonFunc.SetJqGridPageIndex(totalRecords, pageIndex, rowCount);
            var finalList = accDao.Sort(accList, sortColumn, sortOrder)
                                  .Skip((currentPage - 1) * rowCount)
                                   .Take(rowCount);

            var jsonData = new
            {
                total = totalPages,
                page = currentPage,
                records = totalRecords,
                rows = (
                    from m in finalList
                    select new
                    {
                        i = m.ID,
                        cell = new string[] {
                            m.ID.ToString(),
                            m.UserAdmin.UserName,
                            m.Group.GroupName,
                            CommonFunc.ShowActiveImage(m.IsActive),
                            m.CreatedBy,                                                        
                            m.UpdatedBy,                            
                            "<input type=\"button\" class=\"icon edit\" title=\"Cập Nhật\" onclick=\"JS_LIB.popup('/Administration/UserAdmin/Edit/" + m.ID + "', 'Cập Nhật', 400)\" />&nbsp;"
                            + "<input type=\"button\" class=\"icon permission\" title=\"Thay Đổi Mật Khẩu\" onclick=\"JS_LIB.redirect('/Administration/UserAdmin/ChangePassword/" + m.UserAdminId + "')\" />"
                        }
                    }
                ).ToArray()
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }


        //
        // GET: /UserAdmin/Create
        [CrmAuthorizeAttribute(Module = Modules.QL_Nguoi_Dung, Rights = Permissions.Them, ShowInPopup = true)]
        public ActionResult Create()
        {
            ViewData["GroupId"] = new SelectList(groupDao.GetList(true), "GroupId", "GroupName", "");
            return View();
        }

        //
        // POST: /UserAdmin/Create
        [CrmAuthorizeAttribute(Module = Modules.QL_Nguoi_Dung, Rights = Permissions.Them, ShowInPopup = true)]
        [HttpPost]
        public ActionResult Create(FormCollection data)
        {
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            JsonResult result = new JsonResult();
            string userName = data["UserName"];
            string password = CommonFunc.encryptDataMd5(data["Password"], 4);
            string groupId = data["GroupId"];
            bool isActive = (data["IsActive"] == "true");

            Message msg = accDao.Insert(userName, password, groupId, isActive, principal);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }

        //
        // GET: /UserAdmin/Edit/5
        [CrmAuthorizeAttribute(Module = Modules.QL_Nguoi_Dung, Rights = Permissions.Sua, ShowInPopup = true)]
        public ActionResult Edit(int id)
        {
            User_Group user_group = accDao.GetUser_Group(id);
            ViewData["GroupId"] = new SelectList(groupDao.GetList(true), "GroupId", "GroupName", user_group.GroupId);
            return View(user_group);
        }

        //
        // POST: /UserAdmin/Edit/5
        [CrmAuthorizeAttribute(Module = Modules.QL_Nguoi_Dung, Rights = Permissions.Sua, ShowInPopup = true)]
        [HttpPost]
        public ActionResult Edit(FormCollection data)
        {
            string id = data["ID"];
            string userName = data["UserName"];
            string groupId = data["GroupId"];
            bool isActive = (data["IsActive"] == "true");

            // TODO: Add update logic here
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            Message msg = accDao.Update(id, userName, groupId, isActive, principal);
            ShowMessage(msg);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Delete list by ids
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [CrmAuthorizeAttribute(Module = Modules.QL_Nguoi_Dung, Rights = Permissions.Xoa, ShowAtCurrentPage = true)]
        public ActionResult DeleteList(string id)
        {
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            Message msg = null;
            string[] arrDeleteUser = id.Split(',');
            if (arrDeleteUser.Contains(principal.UserData.UserID.ToString()))
            {
                msg = new Message(MessageConstants.E0022, MessageType.Error);
                ShowMessage(msg);
                return RedirectToAction("Index");
            }
            else
            {
                msg = accDao.DeleteList(id);
                ShowMessage(msg);
                return RedirectToAction("Index");
            }
        }

        /// <summary>
        /// Change
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>        
        public ActionResult ChangePassword(int id)
        {
            UserAdmin user = null;
            if (id == 0)
            {
                var principal = HttpContext.User as AuthenticationProjectPrincipal;
                user = accDao.GetById(principal.UserData.UserID);
                ViewData["IsFromMenu"] = true;
            }
            else
            {
                user = accDao.GetById(id);
                ViewData["IsFromMenu"] = false;
            }
            return View(user);            

        }


        /// <summary>
        /// Change
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns> 
        [HttpPost]
        public ActionResult ChangePassword(UserAdmin user)
        {
            var principal = HttpContext.User as AuthenticationProjectPrincipal;
            user.UpdatedBy = principal.UserData.UserName;
            user.UpdateDate = DateTime.Now;
            user.Password = CommonFunc.encryptDataMd5(user.Password, 4);
            Message msg = accDao.ChangePassword(user);
            ShowMessage(msg);
            if (bool.Parse(Request["FromMemu"]))
            {
                return RedirectToAction("ChangePassword/" + user.UserAdminId);
            }
            else
            {
                return RedirectToAction("Index");
            }

        }

        #region Validate


        #endregion
    }
}
